package com.example.wechat.config;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import com.example.project.entity.User;
import com.example.project.utils.ShiroUtils;

import java.util.Map;
import java.util.UUID;

public class HttpSessionHandshakeInterceptor implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                 WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            
            // 1. 获取用户身份信息（这里可以扩展为实际的身份验证逻辑）
            String sessionId = servletRequest.getServletRequest().getSession(false) != null 
                ? servletRequest.getServletRequest().getSession().getId() 
                : UUID.randomUUID().toString();
                
            String token = servletRequest.getServletRequest().getHeader("Authorization");
            String userAgent = servletRequest.getServletRequest().getHeader("User-Agent");
            
            // 2. 将用户信息添加到WebSocket会话属性中
            attributes.put("sessionId", sessionId);
            attributes.put("token", token);
            attributes.put("userAgent", userAgent);
            attributes.put("remoteAddress", servletRequest.getRemoteAddress());
            
            // 3. 获取并存储当前登录用户信息
            Long userId = null;
            
            // 尝试从ShiroSession获取当前用户
            try {
                User currentUser = ShiroUtils.getSysUser();
                if (currentUser != null) {
                    userId = currentUser.getUserId();
                    attributes.put("userId", userId);
                    attributes.put("userName", currentUser.getUserName());
                    attributes.put("loginName", currentUser.getLoginName());
                    System.out.println("WebSocket握手 - 获取到当前用户ID: " + userId);
                } else {
                    // 如果无法获取用户，从会话中查找
                    if (servletRequest.getServletRequest().getSession(false) != null) {
                        Object userObj = servletRequest.getServletRequest().getSession().getAttribute("user");
                        if (userObj instanceof User) {
                            User user = (User) userObj;
                            userId = user.getUserId();
                            attributes.put("userId", userId);
                            attributes.put("userName", user.getUserName());
                            attributes.put("loginName", user.getLoginName());
                            System.out.println("WebSocket握手 - 从会话中获取用户ID: " + userId);
                        }
                    }
                }
            } catch (Exception e) {
                System.out.println("WebSocket握手 - 获取用户信息异常: " + e.getMessage());
            }
            
            // 如果仍然无法获取用户ID，记录错误但不阻止连接
            if (userId == null) {
                System.out.println("WebSocket握手 - 警告：无法获取用户ID，使用默认值1");
                attributes.put("userId", 1L);
                attributes.put("userName", "未知用户");
                attributes.put("loginName", "unknown");
            }
            
            // 记录所有会话属性，用于调试
            if (servletRequest.getServletRequest().getSession(false) != null) {
                System.out.println("WebSocket握手 - 会话存在");
                java.util.Enumeration<String> attributeNames = servletRequest.getServletRequest().getSession().getAttributeNames();
                while (attributeNames.hasMoreElements()) {
                    String attrName = attributeNames.nextElement();
                    Object attrValue = servletRequest.getServletRequest().getSession().getAttribute(attrName);
                    System.out.println("会话属性: " + attrName + " = " + attrValue);
                }
            } else {
                System.out.println("WebSocket握手 - 会话不存在");
            }
            
            // 3. 记录连接日志（可以集成SLF4J日志系统）
            System.out.println("WebSocket连接建立: " + sessionId + " from " + servletRequest.getRemoteAddress());
            
            // 4. 简单的身份验证（生产环境应该使用更严格的验证）
            // 这里简化处理，允许所有连接，实际应该根据业务需求进行验证
            return true;
        }
        return false;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
                             WebSocketHandler wsHandler, Exception exception) {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            
            if (exception == null) {
                // 握手成功
                String sessionId = servletRequest.getServletRequest().getSession(false) != null 
                    ? servletRequest.getServletRequest().getSession().getId() 
                    : "unknown";
                System.out.println("WebSocket握手成功: " + sessionId);
            } else {
                // 握手失败
                System.out.println("WebSocket握手失败: " + exception.getMessage());
            }
        }
    }
}